package com.example.as.untils;

import com.example.as.Service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SocketManager {
    private static ServerSocket ConnectListener;
    @Autowired
    RecordService recordService;
    private static ConcurrentHashMap<String, ObjectOutputStream> socketMap = new ConcurrentHashMap<>(); // 在线名单 static 形 共享数据（便于实时更新）

    @PostConstruct
    public void init() {
        try {
            ConnectListener = new ServerSocket(9999);
            System.out.println("-------------------------------------");
            System.out.println("*服务器通道监听已启动*");
            System.out.println("-------------------------------------");
            new Thread(() -> {
                while (true) {  // 服务端的端口监听者->等待客户端的信道连接请求
                    try {
                        Socket clientSocket = ConnectListener.accept();
                        System.out.println("-------------------------------------");
                        System.out.println("新客户端连接：" + clientSocket.getInetAddress());
                        System.out.println("-------------------------------------");
                        new Thread(new SocketListener(clientSocket, socketMap, recordService)).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ServerSocket getConnectListener() {
        return ConnectListener;
    }

    public static void setConnectListener(ServerSocket connectListener) {
        ConnectListener = connectListener;
    }

    public static ConcurrentHashMap<String, ObjectOutputStream> getSocketMap() {
        return socketMap;
    }

    public static void setSocketMap(ConcurrentHashMap<String, ObjectOutputStream> socketMap) {
        SocketManager.socketMap = socketMap;
    }
}
